import React, { Suspense } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { routerList } from "./routes";

const BeforeEach: React.FC<{ element: JSX.Element; roles?: string[] }> = (
  props
) => {
  // 权限验证
  const role = localStorage.getItem("role") || "";

  if (!props.roles) return props.element;

  else if (props.roles.includes(role)) return props.element;
	
  else return <div>没有权限访问</div>;
};



const renderRouteList = (routes: any[]) => {
  return routes.map((v: any, i: number) => {
    return (
      <Route
        key={i}
        path={v.path}
        element={<BeforeEach element={v.element} roles={v.roles}></BeforeEach>}
      ></Route>
    );
  });
};

const Router = () => {
  return (
    <BrowserRouter>
      <Suspense>
        <Routes>{renderRouteList(routerList)}</Routes>
      </Suspense>
    </BrowserRouter>
  );
};

export default Router;
